package com.safone.thirdattendanceservices.configs;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author xy
 * @date 2020/12/7 13:59
 */
@Component
@Data
@Slf4j
public class ArgsUtil {

    @Autowired
    private final DaHuaConfig daHuaConfig;
    @Autowired
    private  RestTemplate restTemplate;

    private  HttpHeaders  headers;

    public void restTemplateExchange(String apiUrl,String httpMethod,String contentType) {
         String contentMD5 = "";
         String xlcNonce = UUID.randomUUID().toString();
    log.info("随机码:"+xlcNonce);
        //签名
         String date = LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
    log.info("当前系统时间:"+date);
        String stringToSign = httpMethod + "\n"
                + contentMD5 + "\n"
                + contentType + "\n"
                + date + "\n"
                + xlcNonce + "\n"
                + "1.0" + "\n"
                + apiUrl;
        String signature = null;
        try {
            signature = ArgsUtil.hmacSha256(stringToSign, daHuaConfig.getSk());
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("Authorization:{}", "LC-HMAC-SHA256 " + daHuaConfig.getAk()+":"+signature);
        headers = new HttpHeaders();
        // 设置http header
//        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("Accept", MediaType.ALL_VALUE);
        headers.add("Authorization","LC-HMAC-SHA256 " + daHuaConfig.getAk() + ":" + signature);
        headers.add("Content-MD5",contentMD5);
        headers.add("Content-Type", contentType);
        headers.add("X-LC-Date",date);
        headers.add("X-LC-Nonce",xlcNonce);
        headers.add("X-LC-VERSION","1.0");
    }

    /**
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String hmacSha256(String data, String key) throws Exception {
            SecretKeySpec signingKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(signingKey);
            mac.update(data.getBytes("UTF-8"));
            byte[] baseCode = new Base64().encode(mac.doFinal());
            return new String(baseCode, "UTF-8");
    }

}
